package com.tangyee.home;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tangyee.R;
import com.tangyee.home.loadknowledgelist.KnowledgeDetails;
import com.tangyee.app.MineApplication;
import com.tangyee.home.loadknowledgelist.KnowledgeBean;
import com.tangyee.home_blood_center.activities.AddBloodSugarActivity;
import com.tangyee.adapter.ListViewAdapter;
import com.tangyee.home_blood_center.activities.MainActivity;
import com.tangyee.home_blood_center.db.BSRecordHolder;
import com.tangyee.home_blood_center.utils.DateUtil;
import com.tangyee.home_diet.activity.DietActivity;
import com.tangyee.home_exercise_diet.ExerciseAndDietActivity;
import com.tangyee.home_knowledge.acticity.KonwledgeActivity;
import com.tangyee.home_video.HealthyVideo;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


public class HomeFragment extends Fragment {
    //轮播图
    String url1="https://www.tangyee.com/Content/img/carousel/5.jpeg";
    String url2="https://www.tangyee.com/Content/img/carousel/NewCover.png";
    String url3="https://www.tangyee.com/Content/img/carousel/1.jpeg";
    private Banner banner;
    private List<String> list;
//  private List<String> titles;
    //阅读列表+上拉加载
    private ListViewAdapter adapter;
    private ArrayList<HashMap<String, Object>> listItem;
    private ReadListView listview;
    //知识讲坛json接口数据页码
    int page=1;
    //知识讲坛json数据页数据大小
    int pagesize=6;
    // 血糖中心的...
    private TextView timeTextView;
    private TextView valueTextView;
    private LinearLayout mLinearLayout;
    //加载进度条的文字显示
    private TextView tv_foot;
    //判断列表数据是否全部加载完毕
    private Boolean tv_bool=false;
    //图片链接
    String URL="https://www.tangyee.com/Content/upload/images/RecipeImages/";
    private RequestQueue requestQueue;
    public HomeFragment() {
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.layout_home, container, false);
        requestQueue = MineApplication.getRequestQueue();
        initBanner(view);
        loadListView(view);
        return view;
    }
    //初始化轮播图
    private void initBanner(View view){
        list = new ArrayList<String>();
//      titles=new ArrayList<>();
        list.add(url1);
        list.add(url2);
        list.add(url3);
        //添加标题名
//        titles.add("饮食");
//        titles.add("运动");
//        titles.add("医生");
        banner = (Banner) view.findViewById(R.id.banner);
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        //设置标题集合（当banner样式有显示title时）
//      banner.setBannerTitles(titles);
        //设置图片加载器
        banner.setImageLoader(new GlideImageLoader());
        //设置图片集合
        banner.setImages(list);
        //设置自动轮播，默认为true
        banner.isAutoPlay(true);
        //设置轮播时间
        banner.setDelayTime(5000);
        //banner设置方法全部调用完毕时最后调用
        banner.start();
    }

    public void loadListView(View view){
        listview= (ReadListView) view.findViewById(R.id.MyListView);
        /*定义一个以HashMap为内容的动态数组*/
        listItem = new ArrayList<HashMap<String, Object>>();//在数组中存放数据
        tv_foot=(TextView)view.findViewById(R.id.tv_footer);
        //创建网络请求
        StringRequest request = new StringRequest("https://www.tangyee.com/Mobile/Knowledge/GetKnowledgeInfos?page="+page+"&pagesize="+pagesize, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                //使用Gson解析Json数据,获取数据结合
                List<KnowledgeBean> kbList = new Gson().fromJson(response,new TypeToken<List<KnowledgeBean>>(){}.getType());
                for(KnowledgeBean kb: kbList) {
                    final HashMap<String, Object> map = new HashMap<String, Object>();
                    map.put("ItemTitle", kb.getTitle());
                    map.put("ItemId", kb.getKnowID());
                    map.put("ItemAuthor", kb.getAuthor());
                    map.put("ItemCount", kb.getCount());
                    map.put("ItemReleaseDate", kb.getReleaseDate());
                    map.put("ItemSummary", kb.getSummary());
                    map.put("ItemImage",URL+kb.getImage());
                    listItem.add(map);
                }
                //创建适配器绑定数据
                adapter = new ListViewAdapter(HomeFragment.this.getContext(),listItem);
                //绑定适配器
                listview.setAdapter(adapter);//为ListView绑定适配器
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        requestQueue.add(request);//将请求添加到队列中

        page+=1;
        listview.setOnLoadMoreListener(new ReadListView.OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //创建网络请求
                        StringRequest request = new StringRequest("https://www.tangyee.com/Mobile/Knowledge/GetKnowledgeInfos?page="+page+"&pagesize="+pagesize, new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                //使用Gson解析Json数据,获取数据结合
                                List<KnowledgeBean> kbList = new Gson().fromJson(response,new TypeToken<List<KnowledgeBean>>(){}.getType());
                                if(kbList.isEmpty()){
                                    tv_bool=true;
                                }//数据加载完毕显示
                                else{
                                    tv_bool=false;
                                    page++;
                                }
                                for(KnowledgeBean kb: kbList) {
                                    final HashMap<String, Object> map = new HashMap<String, Object>();
                                    map.put("ItemTitle", kb.getTitle());
                                    map.put("ItemId", kb.getKnowID());
                                    map.put("ItemAuthor", kb.getAuthor());
                                    map.put("ItemCount", kb.getCount());
                                    map.put("ItemReleaseDate", kb.getReleaseDate());
                                    map.put("ItemSummary", kb.getSummary());
                                    map.put("ItemImage",URL+kb.getImage());
                                    listItem.add(map);
                                }
                                HomeFragment.this.getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        //当数据更新时同时更新UI
                                        adapter.notifyDataSetChanged();
                                    }
                                });
                            }
                        }, new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {

                            }
                        });
                        requestQueue.add(request);//将请求添加到队列中

                        if(tv_bool){
                            tv_foot.setText("没有数据了^_^");
                        }else {
                            tv_foot.setText("加载中...");
                        }
                        listview.finishLoadMore();
                    }
                }, 500);
            }
        });
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                //这里进入选中阅读列表内容页面
                //Toast.makeText(HomeFragment.this.getActivity(),listItem.get(position-1).get("ItemTitle").toString(),Toast.LENGTH_SHORT).show();
                Intent intent = new Intent();
                intent.putExtra("title",listItem.get(position-1).get("ItemTitle").toString());
                intent.putExtra("id",listItem.get(position-1).get("ItemId").toString());
                intent.setClass(getContext(),KnowledgeDetails.class);
                startActivity(intent);
            }
        });
        //为头布局注册事件点击事件监听
        listview.findViewById(R.id.blood_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getContext(), MainActivity.class);
                startActivity(intent);
            }
        });
        // 设置首页的血糖中心的绿色大圆
        timeTextView = listview.findViewById(R.id.time_card_home);
        valueTextView = listview.findViewById(R.id.home_blood_sugar_value);
        mLinearLayout = listview.findViewById(R.id.blood_center);
        updateValue();

        listview.findViewById(R.id.blood_center).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getContext(), AddBloodSugarActivity.class);
                startActivity(intent);
            }
        });
        listview.findViewById(R.id.blood_right).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(HomeFragment.this.getContext(), "你点击了风险评估", Toast.LENGTH_SHORT).show();
            }
        });
        //四布局
        listview.findViewById(R.id.video).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //Toast.makeText(HomeFragment.this.getContext(), "你点击了视频", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(getContext(), HealthyVideo.class);
                startActivity(intent);
            }
        });
        listview.findViewById(R.id.diet).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //Toast.makeText(HomeFragment.this.getContext(), "你点击了饮食", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(getActivity(),DietActivity.class);
                getActivity().startActivity(intent);
            }
        });
        listview.findViewById(R.id.knows).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), KonwledgeActivity.class);
                getActivity().startActivity(intent);
            }
        });
        listview.findViewById(R.id.sport).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(),ExerciseAndDietActivity.class);
                getActivity().startActivity(intent);
//                Toast.makeText(HomeFragment.this.getContext(), "你点击了运动", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void updateValue() {
        int sign = new Date().getHours()/3 + 1;
        timeTextView.setText(DateUtil.getTimeDescription(sign));
        double value = BSRecordHolder.get(getContext()).getLastBSRecord().getDataBySign(sign);
        if (value == 0) {
            valueTextView.setText("");
            mLinearLayout.setBackgroundResource(R.drawable.add_data_card_home);
        } else {
            mLinearLayout.setBackgroundResource(R.drawable.add_data_card_home_fill);
            valueTextView.setText(value + "");
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        updateValue();
    }

}
